package array.spiralMatrix;

public class O29_SpiralMatrix {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0) return new int[0];
        int len = matrix.length * matrix[0].length;
        int[] arr = new int[len];
        int left = 0, right = matrix[0].length - 1, up = 0, down = matrix.length - 1, index = 0;
        while (index < len) {
            for (int x = left; index < len && x <= right; x++)
                arr[index++] = matrix[up][x];
            up++;
            for (int y = up; index < len && y <= down; y++)
                arr[index++] = matrix[y][right];
            right--;
            for (int x = right; index < len && x >= left; x--)
                arr[index++] = matrix[down][x];
            down--;
            for (int y = down; index < len && y >= up; y--)
                arr[index++] = matrix[y][left];
            left++;
        }
        return arr;
    }

    public static void main(String[] args) {
        O29_SpiralMatrix solution = new O29_SpiralMatrix();
        int[][] matrix = {
//                {1, 2, 3},
//                {8, 9, 4},
//                {7, 6, 5}
                {1, 2, 3, 4},
                {14, 15, 16, 5},
                {13, 20, 17, 6},
                {12, 19, 18, 7},
                {11, 10, 9, 8},
                {1, 1, 1, 1}
        };

        int[] arr = solution.spiralOrder(matrix);
        for (int i : arr) {
            System.out.print(i + "\t");
        }
    }
}
